<template>
  <div class="address-management-container">
    <el-page-header @back="$router.go(-1)">
      <template #content>
        <span class="text-large font-600 mr-3">地址管理</span>
      </template>
    </el-page-header>

    <el-skeleton :rows="6" animated v-if="loading" />
    <el-alert v-if="error" type="error" :title="error.message" show-icon />

    <div style="margin:20px 0">
      <el-button type="primary" @click="handleNewAddress">新建地址</el-button>
    </div>

    <el-table :data="addressList" style="width: 100%" empty-text="暂无收货地址">
      <el-table-column prop="receiver" label="收货人" width="120" />
      <el-table-column prop="mobile" label="电话/手机" width="150" />
      <el-table-column label="所在地区" width="250">
        <template #default="{ row }">
          {{ formatRegion(row.region || {}) }}
        </template>
      </el-table-column>
      <el-table-column prop="detail" label="详细地址" />
      <el-table-column label="操作" width="120">
        <template #default>
          <el-button type="primary" size="small" @click="editDialogVisible = true">修改</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 地址编辑对话框 -->
    <el-dialog v-model="editDialogVisible" title="编辑收货地址" width="600px">
      <el-form :model="addressForm" label-width="100px">
        <el-form-item label="收货人" prop="receiver" 
          :rules="[{ required: true, message: '请输入收货人姓名' }]">
          <el-input v-model="addressForm.receiver" />
        </el-form-item>

        <el-form-item label="手机号" prop="mobile"
          :rules="[
            { required: true, message: '请输入手机号码' },
            { pattern: /^1[3-9]\d{9}$/, message: '手机号格式不正确' }
          ]">
          <el-input v-model="addressForm.mobile" />
        </el-form-item>

        <el-form-item label="所在地区" prop="region"
          :rules="[{ required: true, message: '请选择省市区' }]">
          <el-cascader
            v-model="addressForm.region"
            :options="regionOptions"
            :props="{
              label: 'name',
              value: 'name',
              children: 'districts',
              checkStrictly: true
            }"
            placeholder="请选择省/市/区"
            style="width: 100%"
          />
        </el-form-item>

        <el-form-item label="详细地址" prop="detail"
          :rules="[{ required: true, message: '请输入详细地址' }]">
          <el-input v-model="addressForm.detail" type="textarea" />
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="editDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { mapService } from '@/api/request.js';
import { ref, onMounted, reactive } from 'vue';
import axios from 'axios';
import { ElMessage } from 'element-plus';
import { getToken } from '@/utils/storage';



const apiBase = ref(import.meta.env.VITE_API_BASE || '');
const addressList = ref([]);
const loading = ref(true);
const error = ref(null);

// 编辑对话框相关状态
const editDialogVisible = ref(false);
const addressForm = reactive({
  receiver: '',
  mobile: '',
  region: [],
  detail: ''
});
const regionOptions = ref([]);
const AMAP_KEY = '6376350415aae3592f9f8ef0e005a127'; 

// 处理行政区数据
const processDistricts = (districts) => {
  return districts.map(item => ({
    name: item.name,
    districts: item.districts?.length ? processDistricts(item.districts) : undefined
  }));
};

// 加载行政区数据
const loadRegions = async () => {
  try {
    const { data } = await mapService.get('/config/district', {
      params: {
        key: AMAP_KEY,
        keywords: '中国',
        subdistrict: 3,
        extensions: 'base'
      }
    });
    
    // 调试日志输出
    console.log('行政区数据响应结构:', data);
    
    // 调整数据结构处理
    const baseData = data.districts?.[0]?.districts || [];
    regionOptions.value = processDistricts(baseData);
  } catch (error) {
    ElMessage.error(`行政区数据加载失败: ${error.response?.status || '无响应'}`);
    console.error('行政区加载错误详情:', error);
  }
};

// 提交表单

const isEditing = ref(false);

const handleNewAddress = () => {
  isEditing.value = false;
  Object.assign(addressForm, {
    receiver: '',
    mobile: '',
    region: [],
    detail: ''
  });
  editDialogVisible.value = true;
};


const handleSubmit = async () => {
  try {
    const token = getToken();

    const payload = {
      receiver: addressForm.receiver,
      mobile: Number(addressForm.mobile),
      region: {
        province: addressForm.region[0] || '',
        city: addressForm.region[1] || '',
        district: addressForm.region[2] || ''
      },
      detail: addressForm.detail
    };

    const method = isEditing.value ? 'put' : 'post';
    await axios[method](`${apiBase.value}/user/delivery`, payload, {
      headers: { Authorization: `Bearer ${token}` }
    });

    ElMessage.success(`地址${isEditing.value ? '更新' : '添加'}成功`);
    editDialogVisible.value = false;
    // 刷新地址列表
    const { data } = await axios.get(`${apiBase.value}/user/delivery`, {
      headers: { Authorization: `Bearer  ${token}` }
    });
    addressList.value = Array.isArray(data) ? data : [data];
      addressList.value.forEach(item => {
        item.mobile = String(item.mobile);
        item.region = item.region || {
          province: '',
          city: '',
          district: ''
        };
      });
  } catch (error) {
    ElMessage.error(`操作失败: ${error.message}`);
  }
};

const handleEdit = (row) => {
  isEditing.value = true;
  Object.assign(addressForm, {
    receiver: row.receiver,
    mobile: row.mobile,
    region: [row.region.province, row.region.city, row.region.district],
    detail: row.detail
  });
  editDialogVisible.value = true;
};
const formatRegion = (region) => {
  if (!region) return '';
  return `${region.province || ''} ${region.city || ''} ${region.district || ''}`;
};

onMounted(async () => {
  loadRegions();
  try {
    const token = getToken();


    const { data } = await axios.get(`${apiBase.value}/user/delivery`, {
      headers: { Authorization: `Bearer  ${token}` }
    });
    addressList.value = Array.isArray(data) ? data : [data];
      addressList.value.forEach(item => {
        item.mobile = String(item.mobile);
        item.region = item.region || {};
      });
  } catch (err) {
    error.value = err;
    ElMessage.error(err.response?.data || '获取地址失败');
  } finally {
    loading.value = false;
  }
});
</script>

<style scoped>
.address-management-container {
  max-width: 1200px;
  margin: 20px auto;
  padding: 20px;
}
</style>